package com.jingge.autojob.skeleton.cluster.api;

import com.jingge.autojob.skeleton.cluster.model.ClusterNode;
import com.jingge.autojob.skeleton.framework.boot.AutoJobApplication;
import com.jingge.autojob.skeleton.framework.network.client.CachedProxyClient;
import com.jingge.autojob.skeleton.framework.task.AutoJobTask;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 回调客户端
 *
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-22 10:19
 * @email 1158055613@qq.com
 */
public class CallbackClient implements CallbackAPI {
    private static final CachedProxyClient<CallbackAPI> cachedProxyClient = new CachedProxyClient<>(3, CallbackAPI.class);

    public static List<CallbackAPI> getMasterAPIs() {
        List<ClusterNode> nodes = AutoJobApplication
                .getInstance()
                .getClusterManager()
                .getClusterContext()
                .getMasters();
        return nodes
                .stream()
                .map(cachedProxyClient::getInstance)
                .collect(Collectors.toList());
    }

    private CallbackClient() {
    }

    public static CallbackClient getInstance() {
        return InstanceHolder.CALLBACK_CLIENT;
    }

    @Override
    public Boolean refreshed(AutoJobTask refreshedTask) {
        getMasterAPIs().forEach(api -> api.refreshed(refreshedTask));
        return true;
    }

    private static class InstanceHolder {
        static final CallbackClient CALLBACK_CLIENT = new CallbackClient();
    }
}
